var express = require('express');
var router = express.Router();


const {getmd5}=require("../utils/config")



var {v4} = require('uuid');
// console.log(v4());



const DB = require("../utils/db")



router.post("/register",async (req,res,next)=>{
    // 期望前端传递三个参数:username  password  password2
    let  {username,password,password2}=req.body
    if(!username){
        next("请输入用户名")
        return
    }
    if(!password){
        next("请输入密码")
        return
    }
    if(!password2){
        next("请输入再次输入密码")
        return
    }

    if(password!=password2){
        next("两次输入的密码不一致")
        return
    }


    // 查询此账号是否可用（username在数据库中是否存在）
    let  sql=`select  *  from e_member where username="${username}"`
    let  [err,result]=await DB(sql)
    // console.log(result);
    if(err){
        next("注册失败")
        return
    }

    if(result.length>0){
        next("此用户名太火了，请换一个")
        return
    }
    

    // 执行注册
    // new Date().getTime() 获取当前的时间戳
    // Date.now()
    let  newpassword=getmd5(password)

    let sql1=`insert  into  e_member(mid,username,password,createdate) 
              values("${v4()}","${username}","${newpassword}","${ Date.now() }")`
    let [err1,result1]=await DB(sql1)

    if(err1){
        next("系统崩溃了，请稍后重试")
        return
    }


    res.send({
        status:200,
        msg:"注册成功",
        userids:result1.insertId
    })
})





module.exports = router;